﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Repository;
using YouWei.Utility;
using YouWei.Utility.Logging;

namespace YouWei.Infrastructure.Service
{
    /// <summary>
    /// 支付服务
    /// </summary>
    public class UserCardPayService
    {
        RefundRepository refundRepository = new RefundRepository();
        PaymentRepository paymentRepository = new PaymentRepository();
        UserCardRelaRepository relaRepository = new UserCardRelaRepository();
        UserInfoRepository userRepository = new UserInfoRepository();
        UserCardService _userCardService = new UserCardService();

        #region 业务Id转换

        /// <summary>
        /// 本地业务转换成交易业务
        /// </summary>
        /// <param name="BusinessId"></param>
        /// <returns></returns>
        public string BusinessIdToTradeNum(int businessId)
        {
            return businessId + "_" + DateTime.Now.ToString("MMddHHmmss");
        }

        /// <summary>
        /// 交易业务转换成本地业务
        /// </summary>
        /// <param name="tradeNum"></param>
        /// <returns></returns>
        public int TradeNumToBusinessId(string tradeNum)
        {
            int result = 0;
            if (!string.IsNullOrEmpty(tradeNum))
            {
                int idx = tradeNum.IndexOf("_");
                if (idx > 0)
                {
                    result = EConvert.ToInt(tradeNum.Substring(0, idx));
                }
                else
                {
                    result = EConvert.ToInt(tradeNum);
                }
            }

            return result;
        }

        #endregion


        #region 业务支付成功

        /// <summary>
        /// 业务支付成功
        /// </summary>
        /// <param name="trade_no">平台交易码</param>
        /// <param name="businessId">业务Id</param>
        /// <param name="payType">支付类型</param>
        /// <param name="orderType">业务类型</param>
        /// <returns></returns>
        public bool PaySucess(string trade_no, int businessId, BusinessTypeTypeEnum businessType)
        {
            Payment pay = paymentRepository.GetPaymentByTradeNo(trade_no, (int)businessType);
            if (pay != null)
            {
                return false;
            }

            //查询卡号
            var rela=  relaRepository.SingleOrDefault(businessId);
            if (rela == null)
            {
                Log4netLog.Error(new Utility.Logging.ErrorLog() { CreatedDate = DateTime.Now, ErrorMessage = $"业务不存在,支付失败。详情:trade_no={trade_no},businessId={businessId}", RequestMethod = "Pay", Platform = -1 });
                return false;
            }

            if (rela.PayState == (int)PayStateEnum.Payed)
            {
                return true;
            }
            
            //更新卡的关联
            var card = _userCardService.GetList().Where(t => t.Level == 2).FirstOrDefault();
            if (card != null)
            {
                rela.CardId = card.CardId;
            }
            //更新已付款
            rela.PayState = (int)PayStateEnum.Payed;
            rela.UpdatedDate = DateTime.Now;
            relaRepository.Update(rela);

            //添加付款记录
            pay = new Payment
            {
                Price = card.PayPrice,
                BusinessID = businessId,
                PayPlatform = 1,
                IsActive = 1,
                CreatedDate = DateTime.Now,
                BusinessType = 1,
                PlatformCode = trade_no
            };
            paymentRepository.Insert(pay);

            return true;
        }
      
        #endregion

        #region 退款申请

        /// <summary>
        /// 退款申请
        /// </summary>
        /// <param name="businessId">业务</param>
        /// <param name="reason">退款原因</param>
        /// <returns></returns>
        public bool RefundApply(int businessId, string reason)
        {
            //查询卡号
            var rela = relaRepository.SingleOrDefault(businessId);
            if (rela == null)
            {
                Log4netLog.Error(new Utility.Logging.ErrorLog() { CreatedDate = DateTime.Now, ErrorMessage = $"业务不存在,退款失败。详情:businessId={businessId}", RequestMethod = "Pay", Platform = -1 });
                return false;
            }

            if (rela.PayState != (int)PayStateEnum.Payed)
            {
                return false;
            }

            ////记录退款申请
            //Refund refund = new Refund
            //{
            //    BusinessID = businessId,
            //    ApplicationUser = 0,
            //    ApplicationStatus = (int)RefundApplyStatusEnum.WaitAudit,
            //    ApplicationUserName = "",
            //    CreatedDate = DateTime.Now,
            //    IsActive = 1,
            //    RefundType = (int)refundType,
            //    ReasonId = -1,  //其他
            //    ReasonContent = reason
            //};
            //int applyId = RefundApplyOperate.Insert(info);

            return true;
        }

        #endregion
    }
}